#pragma once

#include<iostream>
#include<sys/types.h>
#include<string.h>
#include<sys/socket.h>
#include<stdio.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>

namespace Tclient
{
  class TcpClient
  {
    private:
      std::string Ip;
      int port;
      int sock;
    public:
    TcpClient(char* _ip,int _port):Ip(_ip),port(_port)
    {}
    void Init()
    {
      sock=socket(AF_INET,SOCK_STREAM,0);
      if(sock<0)
      {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
      }
      //不用手动bind
      //不用listen,不用accpet
      
    }
    void Start()
    {
      //链接服务端
      struct sockaddr_in peer;
      peer.sin_family=AF_INET;
      peer.sin_port=htons(port);
      peer.sin_addr.s_addr=inet_addr(Ip.c_str());

      int re=connect(sock,(struct sockaddr*)&peer,sizeof(peer));
      if(re<0)
      {
        exit(3);
      }
      else{
        std::cout<<"connect success"<<std::endl;
      }

      //执行任务
      while(true)
      {
        std::cout<<"请输入:";
        fflush(stdout);
        char cinbuffer[1024];
        memset(cinbuffer,0,sizeof(cinbuffer));
        int s=read(0,cinbuffer,sizeof(cinbuffer));
        cinbuffer[s-1]=0;
        if(strcmp(cinbuffer,"quit")==0)
        {
          return;
        }
        //给服务端，流式可用read，write
        write(sock,cinbuffer,strlen(cinbuffer));

      }

    }
    ~TcpClient()
    {
      close(sock);
    }
  };
}
